<!DOCTYPE html>
<html lang="zh-cn">

<head>
  <meta charset="UTF-8">
  <title>MarkSite</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes">
  <style>
    /* === 主题变量定义 === */
    :root {
      /* --- 浅色主题基础变量 --- */
      --bg-color: #f9f9f9;
      --sidebar-bg: #ffffff;
      --sidebar-border: #e0e0e0;
      --text-color: #2c3e50;
      --link-color: #3498db;
      --hover-bg: #f1f1f1;
      --card-bg: #ffffff;
      --border-radius: 0.50rem;
      --shadow: 0 0.13rem 0.38rem rgba(0, 0, 0, 0.05);
      --font-family: "Segoe UI", "Roboto", "Noto Sans", "思源黑体", "PingFang SC", "Hiragino Sans GB", sans-serif;

      /* --- 统一 UI 元素颜色 --- */
      --scrollbar-track: #f1f1f1;
      --scrollbar-thumb: #ccc;
      --scrollbar-thumb-hover: #bbb;
      --back-to-top-bg: rgba(0, 123, 255, 0.7);
      --back-to-top-hover-bg: rgba(0, 123, 255, 1);
      --code-bg: #efefef;
      --code-border: #ddd;
      --blockquote-bg: #f9f9f9;
      --blockquote-border: #3498db;
      --table-th-bg: #f5f5f5;
      --toc-link-color: #3498db;
      --toc-active-color: #e74c3c;
      --nav-item-hover: #e8f4ff;
    }

    /* === 深色主题 === */
    [data-theme="dark"] {
      --bg-color: #1a1a1a;
      --sidebar-bg: #1e1e1e;
      --sidebar-border: #3a3a3a;
      --text-color: #e0e0e0;
      --link-color: #6cbaff;
      --hover-bg: #2d2d2d;
      --card-bg: #252526;
      --shadow: 0 0.13rem 0.38rem rgba(0, 0, 0, 0.3);

      --scrollbar-track: #2a2a2a;
      --scrollbar-thumb: #555;
      --scrollbar-thumb-hover: #666;
      --back-to-top-bg: rgba(100, 149, 237, 0.8);
      --back-to-top-hover-bg: rgba(100, 149, 237, 1);
      --code-bg: #282c34;
      --code-border: #3a3f4b;
      --blockquote-bg: #2a2a2a;
      --blockquote-border: #5d8bd6;
      --table-th-bg: #2d2d2d;
      --toc-link-color: #6cbaff;
      --toc-active-color: #ff6b6b;
      --nav-item-hover: #2a4d70;
    }

    /* 添加平滑过渡效果（可选） */
    * {
      transition: background-color 0.3s ease,
      color 0.3s ease,
      border-color 0.3s ease,
      box-shadow 0.3s ease;
    }

    code, pre, .code-copy-button, #back-to-top, .nested, #nav-tree span {
      transition: none !important;
    }

    body {
      margin: 0;
      padding: 0;
      font-family: var(--font-family);
      background-color: var(--bg-color);
      color: var(--text-color) !important;
      height: 100vh;
      display: flex;
      overflow: hidden;
    }

    body a {
      color: var(--toc-link-color);
    }

    #layout {
      display: flex;
      width: 100%;
      height: 100%;
    }

    #sidebar {
      width: 15.63rem;
      background-color: var(--sidebar-bg);
      padding: 1.25rem;
      border-right: 0.06rem solid var(--sidebar-border);
      overflow-y: auto;
      box-shadow: 0.06rem 0 0.19rem rgba(0, 0, 0, 0.05);
    }

    #sidebar h2 {
      font-size: 1rem;
      font-weight: 600;
      margin-top: 0;
      margin-bottom: 1rem;
      color: var(--text-color);
      cursor: pointer;
    }

    #nav-tree {
      list-style: none;
      padding-left: 0.63rem;
    }

    #nav-tree li {
      margin: 0.38rem 0;
      position: relative;
    }

    #nav-tree span {
      text-decoration: none;
      color: var(--link-color);
      display: block;
      padding: 0.38rem 0.63rem;
      border-radius: var(--border-radius);
      transition: background-color 0.2s ease;
      pointer-events: auto;
      cursor: pointer;
    }

    #nav-tree span:hover {
      background-color: var(--hover-bg);
    }

    #nav-tree ul {
      display: none;
      padding-left: 1.25rem;
      list-style: none;
    }

    #nav-tree span {
      cursor: pointer;
      padding: 0.38rem 0.63rem;
      border-radius: var(--border-radius);
      transition: background-color 0.2s ease;
      color: var(--link-color);
    }

    #nav-tree span:hover {
      background-color: var(--hover-bg);
    }

    /* 当前导航项高亮（使用属性控制） */
    #nav-tree li[active] > span {
      background-color: var(--nav-item-hover);
      font-weight: 600;
    }

    #content {
      flex: 1;
      padding: 1.25rem;
      overflow-y: auto;
      scroll-behavior: smooth;
    }

    #markdown-content {
      max-width: calc(100% - 18.75rem);
      background-color: var(--card-bg);
      padding: 1.50rem;
      border-radius: var(--border-radius);
      box-shadow: var(--shadow);
      font-family: var(--font-family);
    }

    /* Markdown 样式增强 */
    #markdown-content h1,
    #markdown-content h2,
    #markdown-content h3,
    #markdown-content h4,
    #markdown-content h5,
    #markdown-content h6 {
      margin-top: 1.5em;
      margin-bottom: 0.8em;
      border-bottom: 0.06rem solid #eee;
      padding-bottom: 0.25rem;
      color: var(--text-color);
      font-weight: 600;
    }

    [data-theme="dark"] #markdown-content h1,
    [data-theme="dark"] #markdown-content h2,
    [data-theme="dark"] #markdown-content h3,
    [data-theme="dark"] #markdown-content h4,
    [data-theme="dark"] #markdown-content h5,
    [data-theme="dark"] #markdown-content h6 {
      border-bottom-color: #444;
    }

    #markdown-content h1,
    #markdown-content h2 {
      margin-top: 0;
    }

    #markdown-content p {
      line-height: 1.9;
      margin-bottom: 1.2em;
    }

    #markdown-content li {
      line-height: 1.8;
      margin: 0.25rem 0;
    }

    #markdown-content code {
      /*background-color: #f1f1f1;*/
      border-radius: 0.25rem;
      font-family: 'JetBrains Mono', monospace;
      padding: 1rem;
    }

    #markdown-content pre {
      background-color: #efefef;
      border-radius: 0.38rem;
      overflow-x: auto;
      font-size: 0.88rem;
      font-family: 'JetBrains Mono', monospace;
      border: 0.06rem solid var(--code-border);
      margin: 1rem 0;
      line-height: 1.5;
    }

    #markdown-content blockquote {
      border-left: 0.25rem solid var(--blockquote-border);
      padding: 1rem;
      margin: 1em 0;
      background-color: var(--blockquote-bg);
      color: #aaa;
      font-style: italic;
    }

    #markdown-content table {
      width: 100%;
      border-collapse: collapse;
      margin: 1rem 0;
    }

    #markdown-content th,
    #markdown-content td {
      border: 0.06rem solid var(--code-border);
      padding: 0.63rem 0.75rem;
      text-align: left;
    }

    #markdown-content th {
      background-color: var(--table-th-bg);
      font-weight: bold;
      color: var(--text-color);
    }

    /* 图片宽度适配容器 */
    #markdown-content img {
      max-width: 100%;
      height: auto;
      display: block;
      margin: 1rem 0;
    }

    /* 滚动条样式（Mac风格） */
    ::-webkit-scrollbar {
      width: 0.50rem;
      height: 0.50rem;
    }

    ::-webkit-scrollbar-track {
      background: var(--scrollbar-track);
      border-radius: 0.25rem;
    }

    ::-webkit-scrollbar-thumb {
      background: var(--scrollbar-thumb);
      border-radius: 0.25rem;
    }

    ::-webkit-scrollbar-thumb:hover {
      background: var(--scrollbar-thumb-hover);
    }

    /* 代码块复制按钮 */
    .code-copy-button {
      position: absolute;
      top: 0.50rem;
      right: 0.75rem;
      padding: 0.25rem 0.63rem;
      font-size: 0.81rem;
      background-color: #007bff;
      color: #fff;
      border: none;
      border-radius: 0.25rem;
      cursor: pointer;
      z-index: 10;
      transition: background-color 0.2s ease;
    }

    .code-copy-button:hover {
      background-color: #0056b3;
    }

    .code-copy-button.success {
      background-color: #28a745;
    }

    #back-to-top {
      position: fixed;
      bottom: 1.88rem;
      right: 1.88rem;
      font-size: 1.75rem;
      text-decoration: none;
      color: #fff;
      background-color: var(--back-to-top-bg);
      padding: 0.63rem 0.75rem;
      border-radius: 50%;
      box-shadow: 0 0.25rem 0.63rem rgba(0, 0, 0, 0.2);
      z-index: 1000;
      opacity: 0;
      transition: opacity 0.3s ease, transform 0.3s ease, background-color 0.3s;
      transform: translateY(0.63rem);
      pointer-events: auto;
      cursor: pointer;
    }

    #back-to-top:hover {
      background-color: var(--back-to-top-hover-bg);
      transform: translateY(0);
    }

    #back-to-top.show {
      opacity: 1;
      transform: translateY(0);
    }

    /* 右侧目录样式 */
    #toc-container {
      position: fixed;
      right: 1.25rem;
      top: 1.25rem;
      width: 12.50rem;
      background-color: var(--card-bg);
      border-radius: var(--border-radius);
      box-shadow: 0 0.25rem 0.75rem rgba(0, 0, 0, 0.1);
      padding: 1rem 1.13rem;
      font-size: 0.88rem;
      z-index: 900;
      opacity: 0.9;
      transition: opacity 0.2s ease;
      pointer-events: auto;
      overflow-y: auto;
      max-height: calc(100vh - 5rem);
    }

    #toc-container:hover {
      opacity: 1;
    }

    #toc-container h3 {
      margin: 0 0 0.75rem 0;
      font-weight: 600;
      color: var(--text-color);
      font-size: 0.94rem;
      border-bottom: 0.06rem solid #eee;
      padding-bottom: 0.38rem;
    }

    [data-theme="dark"] #toc-container h3 {
      border-bottom-color: #444;
    }

    #toc ul {
      list-style: none;
      padding-left: 0;
      margin: 0;
    }

    #toc li {
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      margin: 0.25rem 0;
    }

    #toc a {
      color: var(--toc-link-color);
      text-decoration: none;
      display: block;
      padding: 0.13rem 0;
      font-size: 0.84rem;
      text-overflow: ellipsis;
      white-space: nowrap;
      overflow: hidden;
      word-break: break-all;
    }

    #toc a:hover {
      text-decoration: underline;
    }

    #toc a.active {
      color: var(--toc-active-color);
      font-weight: 600;
    }

    #toc a {
      color: var(--link-color);
      text-decoration: none;
      display: block;
      padding: 0.13rem 0;
      font-size: 0.84rem;
    }

    /* 添加层级缩进 */
    #toc > ul > li > a           { padding-left: 0; }
    #toc > ul > li > ul > li > a { padding-left: 0.63rem; }
    #toc > ul > li > ul > li > ul > li > a { padding-left: 1.25rem; }

    /* --- 移动端按钮样式 --- */
    #menu-toggle,
    #toc-toggle {
      position: fixed;
      top: 0.63rem;
      background-color: var(--link-color);
      color: white;
      padding: 0.5rem 0.75rem;
      border-radius: var(--border-radius);
      font-size: 0.88rem;
      cursor: pointer;
      z-index: 1001;
      display: none;
      opacity: 0.95;
      user-select: none;
    }

    #menu-toggle {
      left: 0.63rem;
    }

    #toc-toggle {
      right: 0.63rem;
    }

    /* --- 平板及以下：隐藏右侧目录，改为按钮控制 --- */
    @media (max-width: 1024px) {
      #toc-container {
        display: none;
      }

      #toc-toggle {
        display: block;
      }

      #toc-toggle.active + #toc-container {
        display: block;
      }

      #markdown-content {
        max-width: 100%;
      }
    }

    /* --- 手机尺寸：单栏，侧边栏隐藏，由按钮控制 --- */
    @media (max-width: 768px) {
      #layout {
        flex-direction: column;
      }

      #sidebar {
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100vh;
        z-index: 999;
        transform: translateX(-100%);
        transition: transform 0.3s ease;
        box-shadow: 0.25rem 0 0.75rem rgba(0, 0, 0, 0.15);
      }

      #menu-toggle {
        display: block;
      }

      #sidebar.active {
        transform: translateX(0);
      }

      #content,
      #toc-container {
        margin-left: 0 !important;
      }

      /* 防止内容被侧边栏遮挡 */
      body {
        overflow-x: hidden;
      }
    }
  </style>
</head>

<body>
  <div id="layout">
    <!-- 移动端菜单按钮 -->
    <div id="menu-toggle">☰ 菜单</div>
    <div id="toc-toggle">📝 目录</div>

    <nav id="sidebar">
      <h2 id="nav-title">导航</h2>
      <!-- 主题切换按钮 -->
      <div style="margin-bottom: 1rem;">
        <button id="theme-toggle" style="width:100%;padding:0.5rem;font-size:0.88rem;border:none;border-radius:var(--border-radius);cursor:pointer;background:var(--hover-bg);color:var(--text-color);">
          🌙 切换主题
        </button>
      </div>
      <ul id="nav-tree"></ul>
    </nav>
    <main id="content">
      <article id="markdown-content">
        <h1>欢迎</h1>
        <p>选择左侧文档开始阅读。</p>
        <p><a href="../../zip/content.zip">点击下载课件文件</a></p>
      </article>

      <span id="back-to-top" title="回到顶部">
        🚀
      </span>
    </main>
    <!-- 右侧目录 -->
    <div id="toc-container">
      <h3>文章目录</h3>
      <div id="toc"></div>
    </div>
  </div>

  <script src="./style/marked.min.js"></script>
  <script src="./style/highlight.min.js"></script>
  <link rel="stylesheet" href="./style/github.min.css">
  <link rel="stylesheet" href="./style/css2.css">
  <script>
    function renderNavTree(nav, element) {
      nav.forEach(item => {
        const li = document.createElement('li');

        if (item.children) {
          const span = document.createElement('span');
          span.textContent = item.name;
          li.appendChild(span);

          const ul = document.createElement('ul');
          ul.classList.add('nested');
          li.appendChild(ul);

          // 为每个目录节点添加一个唯一标识符
          li.dataset.path = item.path;

          span.onclick = function () {
            const nestedUl = li.querySelector('ul');
            nestedUl.style.display = nestedUl.style.display === 'block' ? 'none' : 'block';
          };

          renderNavTree(item.children, ul);
        } else {
          const span = document.createElement('span');
          span.textContent = item.name;
          span.onclick = (e) => {
            e.preventDefault();
            loadMarkdown(item.path);
            highlightNavItem(item.path);

            const sidebar = document.getElementById('sidebar');
            sidebar.classList.remove('active');
          };
          li.appendChild(span);
          // 为文件节点也添加路径标识
          li.dataset.path = item.path;
        }

        element.appendChild(li);
      });
    }

    function loadMarkdown(path) {
      fetch(`/content/${path}`)
        .then(res => res.text())
        .then(text => {
          marked.setOptions({
            highlight: function (code, lang) {
              if (lang && hljs.getLanguage(lang)) {
                return hljs.highlight(code, { language: lang }).value;
              } else {
                return hljs.highlightAuto(code).value;
              }
            }
          });

          const html = marked.parse(text);
          const parser = new DOMParser();
          const doc = parser.parseFromString(html, 'text/html');
          doc.querySelectorAll('img').forEach(img => {
            img.loading = 'lazy';
            img.decoding = 'async';
          });
          document.getElementById('markdown-content').innerHTML = doc.body.innerHTML;
          document.querySelectorAll('#markdown-content pre code').forEach((block) => {
            hljs.highlightElement(block);
          });

          // 更新 URL
          history.pushState(null, '', `?page=${encodeURIComponent(path)}`);

          generateToc();         // 👈 新增：生成目录
          highlightActiveHeading(); // 初始高亮
        });
    }

    function highlightNavItem(path) {
      const navItems = document.querySelectorAll('#nav-tree li');
      navItems.forEach(item => {
        if (item.dataset.path === path) {
          item.setAttribute('active', '');
        } else {
          item.removeAttribute('active');
        }
      });
    }

    function expandPath(path) {
      const navItems = document.querySelectorAll('#nav-tree li');

      for (let i = 0; i < navItems.length; i++) {
        const item = navItems[i];
        const itemPath = item.dataset.path;

        if (itemPath === path) {
          let parent = item.parentElement;
          while (parent && parent.id !== 'nav-tree') {
            if (parent.tagName === 'UL') {
              parent.style.display = 'block';
            }
            parent = parent.parentElement;
          }
          break;
        }
      }
    }

    window.onload = () => {
      fetch('/api/nav-tree')
        .then(res => res.json())
        .then(tree => {
          renderNavTree(tree, document.getElementById('nav-tree'));

          const urlParams = new URLSearchParams(window.location.search);
          const page = urlParams.get('page');

          if (page) {
            loadMarkdown(page);
            expandPath(page);
            highlightNavItem(page);
          } else {
            generateToc();         // 👈 新增：生成目录
            highlightActiveHeading(); // 初始高亮
          }
        })
        .catch(err => {
          console.error("Failed to load navigation tree:", err);
          document.getElementById('nav-tree').innerHTML = "<li>加载目录失败</li>";
        });

      // 启动目录滚动高亮监听（只绑定一次）
      setupTocScrollListener();
    };

    document.getElementById('nav-title').onclick = () => {
      window.location.href = window.location.pathname; // 跳转首页，清除参数
    };

    function addCopyButtonsToCodeBlocks() {
      document.querySelectorAll('pre code').forEach(codeBlock => {
        const pre = codeBlock.parentElement;
        if (!pre.classList.contains('copied')) {
          // 创建按钮
          const button = document.createElement('button');
          button.className = 'code-copy-button';
          button.textContent = '复制';

          // 添加点击事件
          button.addEventListener('click', () => {
            const code = codeBlock.textContent;
            navigator.clipboard.writeText(code).then(() => {
              button.textContent = '已复制';
              button.classList.add('success');
              setTimeout(() => {
                button.textContent = '复制';
                button.classList.remove('success');
              }, 2000);
            }).catch(err => {
              console.error('复制失败:', err);
              button.textContent = '失败';
              button.classList.add('failed');
              setTimeout(() => {
                button.textContent = '复制';
                button.classList.remove('failed');
              }, 2000);
            });
          });

          // 插入按钮到 pre 中
          pre.style.position = 'relative';
          pre.appendChild(button);
          pre.classList.add('copied');
        }
      });
    }

    // 在 Markdown 渲染完成后调用
    const originalLoadMarkdown = window.loadMarkdown;
    window.loadMarkdown = function (path) {
      originalLoadMarkdown(path);

      // 所有异步操作延时确保 DOM 渲染完成
      setTimeout(() => {
        scrollToTop();
        addCopyButtonsToCodeBlocks();
        addTargetBlankToLinks();
      }, 100);
    };

    // 1. 加载新内容后平滑滚动到顶部
    function scrollToTop() {
      document.getElementById('content').scrollTo({
        top: 0,
        behavior: 'smooth'
      });
    }

    // 2. 自动为非同域/非锚点的 a 链接添加 target="_blank" 和 rel="noopener"
    function addTargetBlankToLinks() {
      const content = document.getElementById('markdown-content');
      const links = content.querySelectorAll('a');

      links.forEach(link => {
        const href = link.getAttribute('href');

        // 如果是空链接、锚点（#开头）、或以 mailto:/tel: 等协议开头，不处理
        if (!href || href.startsWith('#') || href.startsWith('mailto:') || href.startsWith('tel:') || href.startsWith('javascript:')) {
          return;
        }

        // 判断是否为站内相对路径（可扩展判断 domain）
        const isInternalLink = href.startsWith('/') ||
          href.includes(window.location.host) ||
          /^\.\.?\//.test(href); // 匹配 ../ 或 ./

        if (!isInternalLink) {
          link.setAttribute('target', '_blank');
          link.setAttribute('rel', 'noopener noreferrer');
        }
      });
    }

    // 获取或创建回到顶部按钮
    const backToTopButton = document.getElementById('back-to-top');

    // 监听滚动事件
    document.getElementById("content").addEventListener('scroll', () => {
      if (document.getElementById("content").scrollTop > 300) { // 滚动超过18.75rem时显示
        backToTopButton.classList.add("show");
      } else {
        backToTopButton.classList.remove("show");
      }
    });

    // 点击按钮平滑滚动回顶部
    backToTopButton.addEventListener('click', () => {
      scrollToTop();
    });

    // ========== 自动生成右侧目录 TOC（仅一级、二级、三级标题）==========
    function generateToc() {
      const content = document.getElementById('markdown-content');
      const headings = content.querySelectorAll('h1, h2, h3'); // 只取 h1~h3
      const toc = document.getElementById('toc');
      toc.innerHTML = ''; // 清空旧目录

      if (headings.length === 0) {
        return;
      }

      const tocList = document.createElement('ul'); // 根列表
      const stack = [tocList]; // 栈：保存当前层级对应的 ul 元素

      headings.forEach((heading, index) => {
        if (!heading.id) {
          heading.id = 'heading-' + index; // 生成唯一 ID
        }

        const level = parseInt(heading.tagName.charAt(1), 10); // 1, 2, 或 3
        const link = document.createElement('a');
        link.href = '#' + heading.id;
        link.textContent = heading.textContent.trim();

        // 点击滚动并高亮
        link.onclick = function (e) {
          e.preventDefault();
          const target = document.getElementById(heading.id);
          if (target) {
            window.location.hash = heading.id;
            target.scrollIntoView({ behavior: 'smooth', block: 'start' });
            setTimeout(() => highlightActiveHeading(), 100);
          }
        };

        const li = document.createElement('li');
        li.appendChild(link);

        // 调整栈：确保当前栈顶是 level-1 对应的 ul
        while (stack.length >= level) {
          stack.pop(); // 弹出过深的层级
        }

        // 如果当前栈长度小于 level-1，说明断层了（理论上不会）
        if (stack.length < level - 1) {
          console.warn('TOC 层级异常:', heading);
          return;
        }

        // 获取当前应插入的 ul（父级列表）
        const parentUl = stack[stack.length - 1];
        if (parentUl) {
          parentUl.appendChild(li);
        } else {
          tocList.appendChild(li);
        }

        // 若该标题还能有子标题，则为其创建 ul 并压入栈
        if (level < 3) {
          const nestedUl = document.createElement('ul');
          li.appendChild(nestedUl);
          stack.push(nestedUl); // 下一层级将插入此 ul
        }
      });

      toc.appendChild(tocList);
    }

    // 高亮当前可视区域内的标题
    function highlightActiveHeading() {
      const contentEl = document.getElementById('content');
      const headings = Array.from(document.querySelectorAll('#markdown-content h1, h2, h3'))
              .map((h, idx) => {
                if (!h.id) h.id = `heading-${idx}`;
                return {
                  id: h.id,
                  top: h.offsetTop
                };
              });

      const scrollTop = contentEl.scrollTop;
      const middleLine = scrollTop + 100; // 触发线

      let activeId = null;
      for (const h of headings) {
        if (h.top <= middleLine) {
          activeId = h.id;
        } else break;
      }

      document.querySelectorAll('#toc a').forEach(a => {
        a.classList.toggle('active', a.getAttribute('href') === '#' + activeId);
      });
    }

    // 页面滚动时更新高亮
    function setupTocScrollListener() {
      const contentEl = document.getElementById('content');
      let ticking = false;

      const update = () => {
        highlightActiveHeading();
        ticking = false;
      };

      contentEl.addEventListener('scroll', () => {
        if (!ticking) {
          requestAnimationFrame(update);
          ticking = true;
        }
      });
    }

    // ========== 动态 rem 基准调整（基于 1920 设计稿）==========
    function resizeFont() {
      const baseWidth = 1920;        // 设计稿宽度
      const baseFontSize = 16;       // 在 baseWidth 下 1rem 对应的像素值
      const currentWidth = window.innerWidth;

      // 计算当前应设置的根字体大小
      let fontSize = (currentWidth / baseWidth) * baseFontSize;

      // 可选：限制最小字号，防止过小（如最小 10px）
      fontSize = Math.max(fontSize, 10);

      document.documentElement.style.fontSize = fontSize + 'px';
    }

    // 初始化
    resizeFont();

    // 窗口变化时重新计算（防抖优化）
    let resizeTimer;
    window.addEventListener('resize', () => {
      clearTimeout(resizeTimer);
      resizeTimer = setTimeout(resizeFont, 100); // 防抖 100ms
    });

    // ========== 主题切换功能 ==========
    const themeToggle = document.getElementById('theme-toggle');

    function setTheme(theme) {
      if (theme === 'dark') {
        document.documentElement.setAttribute('data-theme', 'dark');
      } else {
        document.documentElement.removeAttribute('data-theme');
      }
      localStorage.setItem('preferred-theme', theme);
      updateToggleButton();
    }

    function toggleTheme() {
      const current = localStorage.getItem('preferred-theme');
      const newTheme = current === 'dark' ? 'light' : 'dark';
      setTheme(newTheme);
    }

    function updateToggleButton() {
      const current = localStorage.getItem('preferred-theme');
      const isDark = current === 'dark';
      themeToggle.textContent = isDark ? '☀️ 浅色模式' : '🌙 深色模式';
    }

    document.addEventListener('DOMContentLoaded', () => {
      const saved = localStorage.getItem('preferred-theme');
      const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
      const initialTheme = saved || (prefersDark ? 'dark' : 'light');
      setTheme(initialTheme);
      themeToggle?.addEventListener('click', toggleTheme);
    });

    // === 移动端菜单与目录按钮控制 ===
    document.getElementById('menu-toggle').addEventListener('click', function () {
      const sidebar = document.getElementById('sidebar');
      sidebar.classList.toggle('active');
    });

    document.getElementById('toc-toggle').addEventListener('click', function () {
      const tocContainer = document.getElementById('toc-container');
      tocContainer.style.display = tocContainer.style.display === 'block' ? 'none' : 'block';
      this.classList.toggle('active');
    });

    // 点击页面其他区域关闭侧边栏或目录
    document.addEventListener('click', function (e) {
      const tocContainer = document.getElementById('toc-container');
      const tocToggle = document.getElementById('toc-toggle');

      // 如果点击不是在目录按钮或目录容器内，则关闭目录
      if (tocContainer.style.display === 'block' && !tocContainer.contains(e.target) && !tocToggle.contains(e.target)) {
        tocContainer.style.display = 'none';
        tocToggle.classList.remove('active');
      }
    });
  </script>
</body>

</html>